<template>
  <s-layout>
    <view class="page-container">
      <!-- 轮播图 -->
      <swiper class="swiper-container" autoplay circular indicator-dots>
        <swiper-item
          v-for="(image, index) in detailData.image"
          :key="index"
        >
          <image :src="image" mode="aspectFill" class="carousel-image"></image>
        </swiper-item>
      </swiper>
      <view class="check-box">
        <view class="check-box-border">
          <view class="header-box">
            <view class="header-box-shang">
              <text class="title">{{ detailData.title }}</text>
              <view>
                <view
                  class="list-item-right-tag-box2"
                  style="margin-top: 3rpx; margin-right: 3rpx"
                >
                  <view class="list-item-right-tag-box-text2 center">
                    <view>{{ detailData.name }}</view>
                  </view>
                </view>
              </view>
            </view>
            <view class="header-box-xia">
              <view class="header-box-xia-txt2-border">
                <view>
                  <view class="list-item-right-tag-box2">
                    <view class="list-item-right-tag-box-text2 center">
                      <view>整改次数：1次</view>
                    </view>
                  </view>
                </view>
                <view>
                  <view class="list-item-right-tag-box">
                    <view class="list-item-right-tag-box-text center">
                      <view>{{ detailData.address }}</view>
                    </view>
                  </view>
                </view>
                <view>
                  <view class="list-item-right-tag-box3">
                    <view class="list-item-right-tag-box-text3 center">
                      <view>{{ detailData.time }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="check-box">
        <view class="check-box-border">
          <fui-section
            title="检查视频"
            line-width="3px"
            line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
            isLine
            marginBottom="25"
            padding="20rpx 0"
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              --fui-section-line-color: #19be6b;
            "
          ></fui-section>
          <view class="check-content video-list-container">
            <scroll-view scroll-x class="video-scroll-view">
              <view class="video-item" v-for="(item, index) in detailData.video" :key="index">
                <su-video
                  style="
                    width: 100%;
                    height: 100%;
                  "
                  :src="item"
                  :poster="item"
                />
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
      <view class="check-box">
        <view class="check-box-border">
          <fui-section
            title="检查内容"
            line-width="3px"
            line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
            isLine
            marginBottom="25"
            padding="10rpx 0"
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              --fui-section-line-color: #19be6b;
            "
          ></fui-section>
          <view class="check-content">
            <view class="check-item" v-html="detailData.content"></view>
          </view>
        </view>
      </view>

      <view class="check-box">
        <view class="check-box-border">
          <fui-section
            title="检查文件"
            line-width="3px"
            line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
            isLine
            marginBottom="25"
            padding="10rpx 0"
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              --fui-section-line-color: #19be6b;
            "
          ></fui-section>
          <view class="check-content file-list-container">
            <view v-if="detailData.file && detailData.file.length > 0">
              <view class="file-item" v-for="(fileUrlInArray, index) in detailData.file" :key="index" @click="openFile(fileUrlInArray)">
                <!-- Assuming the file URL is directly the string in the array as per the image -->
                <!-- We need to extract name and type from the URL or assume a structure -->
                <image :src="getFileIcon(extractFileTypeFromUrl(fileUrlInArray))" class="file-icon"></image>
                <text class="file-name">{{ extractFileNameFromUrl(fileUrlInArray) }}</text>
              </view>
            </view>
            <view v-else class="empty-files">
              <text>暂无检查文件</text>
            </view>
          </view>
        </view>
      </view>
      <view class="situation-box">
        <view class="situation-border">
          <fui-section
            title="检查情况"
            line-width="3px"
            line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
            isLine
            marginBottom="25"
            padding="10rpx 0"
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              --fui-section-line-color: #19be6b;
            "
          ></fui-section>
          <view class="situation-content">
            <view class="situation-content-txt">{{
              detailData.situtation
            }}</view>
            <!-- <image
              class="situation-img"
              v-if="detailData.status == '1'"
              src="@/static/tabs/治理中.png"
              mode="scaleToFill"
            />
            <image
              class="situation-img"
              v-else-if="detailData.status == '2'"
              src="@/static/tabs/治理完成.png"
              mode="scaleToFill"
            />
            <image
              v-else-if="detailData.status == '3'"
              class="situation-img"
              src="@/static/tabs/无隐患.png"
              mode="scaleToFill"
            /> -->
          </view>
        </view>
      </view>

      <view class="modify-box">
        <view class="modify-border">
          <fui-section
            title="整改记录"
            line-width="3px"
            line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
            isLine
            marginBottom="25"
            padding="10rpx 0"
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              --fui-section-line-color: #19be6b;
            "
          ></fui-section>
          <view class="modify-content">
            <view
              v-for="(item, index) in rectificationRecords"
              :key="index"
              style="margin-bottom: 10px"
            >
              <view class="imut_map_box_message_title">{{ item.sr_measure }}</view>
              <!-- ……组件 -->
              <view
                class="cicon-more"
                style="
                  font-size: 50rpx;
                  float: right;
                  position: relative;
                  top: -70rpx;
                  right: 0rpx;
                "
                @click.stop="editBoxShow(item)"
              ></view>
              <view class="editBox" v-if="activeEditItemId === item.id">
                <view
                  class="editBox-item"
                  @click.stop="
                    sheep.$router.go(`/pages/qy/hiddendanger/update`, {
                      id: detailData.id,
                      zhenggai: true,
                    });
                    activeEditItemId = null; // Hide menu after clicking
                  "
                >
                  <text class="editBox-item-text">修改</text>
                </view>
                
                <view class="editBox-item" @click.stop="deleteItem(item)">
                  <!-- confirmDelete already handles hiding the menu -->
                  <text class="editBox-item-text">删除</text>
                </view>
              </view>
              <view class="imut_map_box_message_tag" style="display: flex">
                <view class="imut_map_box_message_tag_type">{{
                  item.sr_people
                }}</view>
                <view style="display: flex">
                  <view class="imut_map_box_message_tags">{{
                    detailData.address
                  }}</view>
                </view>
              </view>

              <view class="imut_map_box_message_time_view flex">
                <view class="blue-txt">{{ item.sr_status }}</view>
                <view class="imut_map_box_message_time"
                  >发布时间：{{ item.sr_time }}</view
                >
              </view>

              <view class="imut_map_box_message_detail">{{
                item.description
              }}</view>

              <view class="imut_map_box_message_image flex" @click="previewImage(item.sr_images, image)">
                <image
                  v-for="(image, imgIndex) in item.sr_images"
                  :key="imgIndex"
                  class="imut_map_box_message_image_item"
                  :src="image"
                  mode="aspectFill"
                />
              </view>

              <!-- Display Videos -->
              <view class="attachment-section" v-if="item.sr_videos && item.sr_videos.length > 0">
                <text class="attachment-title">相关视频:</text>
                <view class="video-list-inline">
                  <view class="video-item-inline" v-for="(videoUrl, videoIndex) in item.sr_videos" :key="videoIndex">
                    <su-video :src="videoUrl" :controls="true" style="width: 100%; height: 150px;"></su-video>
                  </view>
                </view>
              </view>

              <!-- Display Files -->
              <view class="attachment-section" v-if="item.sr_files && item.sr_files.length > 0">
                <text class="attachment-title">相关文件:</text>
                <view class="file-list-inline">
                  <view class="file-item-inline" v-for="(fileUrl, fileIndex) in item.sr_files" :key="fileIndex" @click="openFile(fileUrl)">
                    <image :src="getFileIcon(extractFileTypeFromUrl(fileUrl))" class="file-icon-inline"></image>
                    <text class="file-name-inline">{{ extractFileNameFromUrl(fileUrl) }}</text>
                  </view>
                </view>
              </view>

              <view class="line"></view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup lang="ts">
import { ref } from "vue";
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";

const detailData = ref({});
const rectificationRecords = ref([]);

const pdfIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_acrobat.png";
const wordIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_word.png";
const genericFileIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white.png";
const excelIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_excel.png";
const pptIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_powerpoint.png";

const extractFileNameFromUrl = (fileUrl) => {
  if (!fileUrl || typeof fileUrl !== 'string') return '未知文件';
  try {
    const url = new URL(fileUrl);
    const pathname = url.pathname;
    const parts = pathname.split('/');
    return parts[parts.length - 1] || '未知文件';
  } catch (e) {
    const parts = fileUrl.split('/');
    return parts[parts.length - 1] || '未知文件';
  }
};

const extractFileTypeFromUrl = (fileUrl) => {
  if (!fileUrl || typeof fileUrl !== 'string') return '';
  const extension = fileUrl.split('.').pop();
  return extension ? extension.toLowerCase() : '';
};

const getFileIcon = (fileType) => {
  const type = fileType ? fileType.toLowerCase() : '';
  if (type.includes('pdf')) return pdfIconUrl;
  if (type.includes('doc') || type.includes('docx')) return wordIconUrl;
  if (type.includes('xls') || type.includes('xlsx')) return excelIconUrl;
  if (type.includes('ppt') || type.includes('pptx')) return pptIconUrl;
  return genericFileIconUrl;
};

const openFile = (fileUrl) => {
  // Implement file opening logic, e.g., using uni.downloadFile and uni.openDocument
  // For web, you might use window.open(file.url)
  if (fileUrl) {
    // #ifdef H5
    window.open(fileUrl, '_blank');
    // #endif
    // #ifndef H5
    uni.downloadFile({
      url: fileUrl, // Use fileUrl directly
      success: function (res) {
        var filePath = res.tempFilePath;
        // Instead of opening, prompt that download is complete.
        // uni.openDocument is for previewing, not direct download prompting.
        // #ifdef MP-WEIXIN
        // In WeChat Mini Program, openDocument is the way to handle downloaded files for preview.
        uni.openDocument({
          filePath: filePath,
          showMenu: true, // For some file types, this allows forwarding or saving to cloud drive
          success: function (res) {
            console.log('打开文档成功（微信小程序）');
          },
          fail: function (err) {
            console.error('打开文档失败（微信小程序）：', err);
            uni.showToast({
              title: '打开文件失败: ' + (err.errMsg || ''),
              icon: 'none'
            });
          }
        });
        // #else
        // For other non-H5 platforms, try to save the file
        uni.saveFile({
          tempFilePath: filePath,
          success: function (saveRes) {
            uni.showToast({
              title: '已保存到：' + saveRes.savedFilePath,
              icon: 'none',
              duration: 3000
            });
            console.log('文件已保存到：', saveRes.savedFilePath);
          },
          fail: function (saveErr) {
            console.error('保存文件失败：', saveErr);
            uni.showToast({
              title: '保存文件失败: ' + (saveErr.errMsg || ''),
              icon: 'none'
            });
            // Fallback: if saveFile fails, at least notify about the temp path
            uni.showToast({
              title: '下载完成，临时路径：' + filePath,
              icon: 'none',
              duration: 3000
            });
          }
        });
        // #endif
      },
      fail: function(err){
        uni.showToast({
          title: '下载失败: ' + (err.errMsg || ''),
          icon: 'none'
        });
      }
    });
    // #endif
  } else {
    uni.showToast({
      title: '文件链接无效',
      icon: 'none'
    });
  }
};
// ……组件
const activeEditItemId = ref(null);
// 点击"更多"图标时触发的函数
const editBoxShow = (item) => {
  // 获取被点击项目的 ID
  const currentItemId = item.id;
  // 检查：如果当前点击的项目的编辑框 *已经* 是显示的那个
  if (activeEditItemId.value === currentItemId) {
    // 就将其隐藏（通过将 activeEditItemId 设置回 null）
    activeEditItemId.value = null;
  } else {
    // 否则，显示当前点击项目的编辑框
    // 这会自动隐藏之前可能打开的任何其他项目的编辑框
    activeEditItemId.value = currentItemId;
  }
  console.log("当前显示编辑框的项目 ID:", activeEditItemId.value);
};

function deleteItem(item) {
  const params = {
    sr_id: item.sr_id,
  };
  sheep.$api.qy_hiddendanger.deleteRecord(params).then((res) => {
    if (res.code == 200) {
      uni.showToast({
        title: "删除成功",
        icon: "none",
      });
    }
    get(onloadParams.value);
  });
}
const onloadParams = ref({});
const get = (params) => {
  sheep.$api.qy_hiddendanger.detail(params).then((res) => {
    detailData.value = res.data.screen_info;
    rectificationRecords.value = res.data.screen_records;
  });
};
onLoad((options) => {
  onloadParams.value = {
    s_id: options.id,
    company_id: sheep.$store("user").userInfo.company_id,
  };
  get(onloadParams.value);
  // Mock file data for testing based on the provided image structure
  // detailData.value.file = [
  //   {
  //     url: 'https://assess.yuejin-tech.com/upload/company/drill/2025-05-27/844US1BIW67UDzR7d6e10be3ab68711a6eb3316950.pdf',
  //     name: '示例文件.pdf', // Assuming name comes from parsing the URL or another field
  //     type: 'pdf' // Assuming type comes from parsing the URL or another field
  //   },
  //   {
  //     url: 'https://assess.yuejin-tech.com/upload/company/drill/2025-05-27/anotherFile.docx',
  //     name: '另一个文件.docx',
  //     type: 'docx'
  //   }
  // ];
  // Ensure detailData.value.file is populated by the get() call, 
  // the mock data above is just for structural reference if needed during development without backend.
});

const previewImage = (urls, current) => {
  uni.previewImage({
    urls: urls, // 需要预览的图片http链接列表
    current: current, // 当前显示图片的http链接
    loop: true,
  });
};
</script>

<style lang="scss">
page {
  background-color: #f0f3f8;
  height: 100%;
}
.page-container {
  width: 96%;
  margin: auto;
}
.swiper-container {
  width: 100%;
  height: 380rpx;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 100%;
  display: block; /* 确保图片以块级元素显示 */
}

.check-box {
  background-color: #fff;
  margin-top: 15rpx;
  border-radius: 5px;
}
.check-box-border {
  width: 94%;
  margin: auto;
  padding: 20rpx 0;
}
.header-box {
  margin-bottom: rpx;
  border-left: 0.25rem solid rgb(41, 121, 255);
  .title {
    margin-left: 10rpx;
    font-size: 44rpx;
    font-weight: 700;
    color: #1a1a1a;
    max-width: 70%;
  }
  .header-box-shang {
    display: flex;
    justify-content: space-between;
  }
  .list-item-right-tag-box {
    background-color: #f7ebde;
    display: inline-block;
    margin-bottom: 5rpx;
    padding: 3rpx 13rpx;
    border-radius: 8px;
    margin-left: 10rpx;
  }

  .list-item-right-tag-box-text {
    height: 30rpx;
    font-size: 20rpx;
    font-weight: 550;
    color: #ff6633;
  }
  .list-item-right-tag-box2 {
    background-color: #dee6f7;
    display: inline-block;
    margin-bottom: 5rpx;
    padding: 3rpx 13rpx;
    border-radius: 8px;
  }

  .list-item-right-tag-box-text2 {
    height: 30rpx;
    font-size: 20rpx;
    font-weight: 550;
    color: #0038b1;
  }
  .list-item-right-tag-box3 {
    background-color: #ebeaea;
    display: inline-block;
    margin-bottom: 5rpx;
    padding: 3rpx 13rpx;
    border-radius: 8px;
    margin-left: 10rpx;
  }

  .list-item-right-tag-box-text3 {
    height: 30rpx;
    font-size: 20rpx;
    font-weight: 550;
    color: #666;
  }
  .header-box-xia {
    margin-left: 10rpx;
    margin-top: 3rpx;
  }
  .header-box-xia-txt1 {
    color: #666;
    font-size: 22;
  }
  .header-box-xia-txt2-border {
    display: flex;
    margin-top: 10rpx;
  }
  .status-tag {
    padding: 16rpx 32rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #fff;
    @include flex(row, center, center);
    gap: 10rpx;
  }
}
/* 在线链接服务仅供平台体验和调试使用，平台不承诺服务的稳定性，企业客户需下载字体包自行发布使用并做好备份。 */
@font-face {
  font-family: "阿里妈妈数黑体 Bold";
  font-weight: 700;
  src: url("//at.alicdn.com/wf/webfont/5y8BnD5qQg2n/rrtM1LP5iUzZ.woff2")
      format("woff2"),
    url("//at.alicdn.com/wf/webfont/5y8BnD5qQg2n/o0Q3cO7cUfPA.woff")
      format("woff");
  font-display: swap;
}
.video-list-container {
  width: 100%;
  overflow: hidden;
}
.video-scroll-view {
  white-space: nowrap;
  width: 100%;
  /* Ensure the scroll view itself doesn't add extra padding that prevents full width */
  font-size: 0; /* hack to remove inline-block spacing if any */
}
.video-item {
  display: inline-block;
  width: 100%; /* Each video item takes full width of the container */
  height: 300rpx;
  vertical-align: top;
  background-color: #f0f0f0;
  /* margin-right: 20rpx; */ /* Remove right margin if videos are full width */
}
/* If you still want spacing for multiple videos, it's better to handle it via scroll-view padding or specific logic if needed */
/* .video-item:not(:last-child) {
  margin-right: 20rpx;
} */

.file-list-container {
  margin-top: 15rpx;
}
.file-item {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;
  cursor: pointer;
}
.file-item:last-child {
  border-bottom: none;
}
.file-icon {
  width: 48rpx;
  height: 48rpx;
  margin-right: 20rpx;
}
.file-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.empty-files {
  text-align: center;
  color: #999;
  padding: 20rpx 0;
  font-size: 28rpx;
}
.check-title {
  font-family: "阿里妈妈数黑体 Bold";
  font-weight: 700;
  font-size: 32rpx;
}
.check-content {
  margin-top: 15rpx;
}
.check-item {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6; /* 行高 */
  /* text-indent: 2em;  首行缩进两字符 */
}
.situation-box {
  background-color: #fff;
  margin-top: 15rpx;
  border-radius: 5px;
}
.situation-border {
  width: 94%;
  margin: auto;
  padding: 20rpx 0;
}
.situation-title {
  font-family: "阿里妈妈数黑体 Bold";
  font-weight: 700;
  font-size: 32rpx;
}
.situation-img {
  width: 150rpx;
  height: 150rpx;
}
.situation-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.situation-content-txt {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
}
.modify-box {
  background-color: #fff;
  margin-top: 15rpx;
  border-radius: 5px;
  margin: 10px auto;
  box-shadow: 1px 1px 10px #e0e0e0;
}
.modify-border {
  width: 94%;
  margin: auto;
  padding: 20rpx 0;
}
.modify-content {
  width: 92%;
  margin: 0 auto;
  padding: 15px 0;
  z-index: 9999;
}
.modify-content-pic {
  width: 50%;
  height: 300rpx;
  margin: auto;
}
.imut_map_box_message_title {
  color: #333333;
  font-weight: 600;
  font-size: 14px;
}
.imut_map_box_message_tag {
  margin: 10px 0;
  font-weight: 600;
}
.imut_map_box_message_time_view {
  font-size: 11px;
  color: rgb(139, 139, 139);
}
.flex {
  display: flex;
  justify-content: space-between;
}
.imut_map_box_message_detail {
  font-weight: 500;
  color: #333333;
  font-size: 13px;
  margin: 10px 0;
}
.line {
  display: block;
  height: 0.3px;
  width: 100%;
  background-color: rgb(222, 222, 222);
  margin: 13px 0;
}
.imut_map_box_message_tag_type {
  background-color: #3772ff;
  padding: 2px 5px;
  color: #ffffff;
  font-size: 11px;
  letter-spacing: 2px;
  margin-right: 8px;
  border-radius: 5px;
}
.imut_map_box_message_tags {
  color: rgb(83, 83, 83);
  background-color: rgb(232, 232, 232);
  padding: 2px 5px;
  font-size: 11px;
  letter-spacing: 2px;
  margin-right: 8px;
  border-radius: 5px;
}
.imut_map_box_message_image_item {
  width: 200rpx;
  height: 200rpx;
  border-radius: 5px;
  object-fit: cover; /* Ensure images cover the area without distortion */
  cursor: pointer; /* Add cursor pointer for click interaction */
}

.attachment-section {
  margin-top: 15rpx;
}

.attachment-title {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.video-list-inline {
  display: flex;
  flex-wrap: nowrap; /* 不换行，以便横向滚动 */
  overflow-x: auto; /* 允许横向滚动 */
  gap: 10px; /* 视频之间的间距 */
  width: 100%; /* 占满父容器宽度 */
}

.video-item-inline {
  width: calc(33.333% - 10px); /* 每行显示三个视频，减去间距 */
  margin-bottom: 10px;
  position: relative;
  flex-shrink: 0; /* 防止视频项在 flex 容器中被压缩 */
}

.file-list-inline {
  display: flex;
  flex-direction: column; /* Stack files vertically */
  gap: 8rpx;
}

.file-item-inline {
  display: flex;
  align-items: center;
  padding: 8rpx;
  background-color: #f9f9f9;
  border-radius: 4rpx;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.file-item-inline:hover {
  background-color: #f0f0f0;
}

.file-icon-inline {
  width: 32rpx;
  height: 32rpx;
  margin-right: 10rpx;
}

.file-name-inline {
  font-size: 26rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.blue-txt {
  color: #0038b1;
}
.video-section {
  position: relative;
  background: #000;
  width: 90%;
  margin: 20rpx auto;
  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 60rpx;
    background: linear-gradient(transparent, #ecf5ff);
  }
}
// ……组件
.editBox {
    position: absolute;
    right: 0;
    top: 120rpx;
    background-color: #fff;
    width: 130rpx;
    border-radius: 8rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
    z-index: 10;
    overflow: hidden;
    animation: fadeIn 0.3s ease;

    .editBox-item {
      padding: 16rpx;
      text-align: center;
      transition: background-color 0.2s;

      &:hover {
        background-color: #f5f5f5;
      }

      .editBox-item-text {
        font-size: 25rpx;
        color: #333;
      }
    }
  }
</style>
